package com.liuqi.iot.service.impl;

import com.baomidou.dynamic.datasource.annotation.DS;
import com.liuqi.iot.bean.dto.DeviceDataDTO;
import com.liuqi.iot.bean.dto.DeviceHistoryData;
import com.liuqi.iot.bean.query.DeviceHistoryDataAggQuery;
import com.liuqi.iot.bean.query.DeviceHistoryDataQuery;
import com.liuqi.iot.domain.mapper.DeviceHistoryDataMapper;
import com.liuqi.iot.service.DeviceHistoryDataService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.time.ZoneOffset;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 历史数据服务实现 
 * @author Coder Generator 2025-03-22 20:51:27 
 **/
@Service
@DS("td")
public class DeviceHistoryDataServiceImpl implements DeviceHistoryDataService {
    @Autowired
    private DeviceHistoryDataMapper historyDataMapper;

    /**
     * 创建设备子表
     */
    @Override
    @Transactional
    public void createTable(String deviceCode) {
        // 先创建主表
        historyDataMapper.createMainTable();

        // 然后查询子表，如果不存在则进行创建
        List<Map<String, Object>> list = historyDataMapper.queryTable(deviceCode);
        if (CollectionUtils.isEmpty(list)) {
            historyDataMapper.createTable(deviceCode);
        }
    }

    @Override
    public void batchInsert(List<DeviceDataDTO> list) {
        if (CollectionUtils.isEmpty(list)) {
            return;
        }

        // 需要按设备进行归并
        Map<String, List<DeviceHistoryData>> deviceDataMap = list.stream()
                .map(data -> {
                    DeviceHistoryData historyData = new DeviceHistoryData();
                    BeanUtils.copyProperties(data, historyData);
                    historyData.setTs(data.getTs().toInstant(ZoneOffset.ofHours(8)).toEpochMilli());
                    return historyData;
                })
                .collect(Collectors.groupingBy(DeviceHistoryData::getDeviceCode));
        deviceDataMap.forEach(historyDataMapper::batchInsert);
    }

    @Override
    public List<DeviceHistoryData> query(DeviceHistoryDataQuery query) {
        return historyDataMapper.query(query);
    }

    /**
     * 聚合查询
     */
    @Override
    public List<DeviceHistoryData> aggQuery(DeviceHistoryDataAggQuery query) {
        return historyDataMapper.aggQuery(query);
    }
}